<template>
  <div>
    <el-dialog :title="title" :visible.sync="dialogVisible" :before-close="handleCancel" center top="5vh" width="800px">
      <el-form ref="editFormRef" :model="editForm" :rules="rules" label-width="100px" size="small">
        <input readonly type="text" autocomplete="off" name="mobile" class="cus-input" />
        <input readonly type="password" autocomplete="new-password" name="password" class="cus-input" />
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户账号" prop="account">
              <el-input placeholder="请输入用户账号" v-model="editForm.account" autocomplete="off"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="昵称" prop="nickName">
              <el-input placeholder="请输入昵称" v-model="editForm.nickName" autocomplete="off"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="用户姓名" prop="userName">
              <el-input placeholder="请输入用户姓名" v-model="editForm.userName" autocomplete="off"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input placeholder="请输入邮箱" v-model="editForm.email"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="手机号" prop="mobile">
              <el-input placeholder="请输入手机号" v-model="editForm.mobile" autocomplete="off"></el-input>
            </el-form-item>
          </el-col>
          <!-- <input type="text" autocomplete="off" name="mobile" style="position: absolute;left: -10000px;">
          <input type="password" autocomplete="new-password" name="password" style="position: absolute;left: -10000px;"> -->
          <el-col :span="12">
            <el-form-item label="登录密码" prop="password">
              <el-input
                ref="passwordRef1"
                v-show="type === 'text'"
                placeholder="请输入登录密码"
                autocomplete="off"
                :disabled="disabled"
                type="text"
                v-model="editForm.password"
              ></el-input>

              <el-input
                ref="passwordRef2"
                v-show="type === 'password'"
                placeholder="请输入登录密码"
                autocomplete="off"
                :disabled="disabled"
                type="password"
                v-model="editForm.password"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="性别" prop="sex">
              <el-select style="width: 100%" v-model="editForm.sex" placeholder="请选择性别">
                <el-option v-for="item in sexList" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="年龄" prop="age">
              <el-input placeholder="请输入年龄" v-model="editForm.age" autocomplete="off"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="证件类型" prop="idType">
              <el-select style="width: 100%" v-model="editForm.idType" placeholder="请选择证件类型">
                <el-option v-for="item in idTypeList" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="证件号码" prop="idcardNo" v-if="editForm.idType === 0">
              <el-input placeholder="请输入证件号码" v-model="editForm.idcardNo"></el-input>
            </el-form-item>
            <el-form-item label="证件号码" prop="idcardNo" v-else>
              <el-input placeholder="请输入其他" v-model="editForm.idcardNo"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="userShow">
            <el-form-item label="角色" prop="roleNos" class="userFormItem">
              <el-select style="width: 100%" v-model="editForm.roleNos" multiple placeholder="请选择角色">
                <el-option v-for="item in roleList" :key="item.roleNo" :label="item.roleName" :value="item.roleNo">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="userShow">
            <el-form-item label="部门" prop="deptName" class="userFormItem">
              <el-input
                ref="deptInput"
                placeholder="请选择部门"
                @focus="deptFocus"
                v-model="editForm.deptName"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="userShow">
            <el-form-item label="岗位" prop="positionId" class="userFormItem">
              <el-select style="width: 100%" v-model="editForm.positionId" placeholder="请选择岗位">
                <el-option
                  v-for="item in positionList"
                  :key="item.positionId"
                  :label="item.positionName"
                  :value="item.positionId"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="员工号" prop="employeeNo" class="userFormItem">
              <el-input placeholder="请输入员工号" v-model="editForm.employeeNo"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="员工卡号" prop="employeeCardNo" class="userFormItem">
              <el-input placeholder="请输入员工卡号" v-model="editForm.employeeCardNo"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户类型" prop="userType" class="userFormItem">
              <el-select style="width: 100%" v-model="editForm.userType" multiple placeholder="请选择用户类型">
                <el-option
                  v-for="item in userTypeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                  :disabled="item.disabled"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户状态" prop="isEnable">
              <el-radio-group v-model="editForm.isEnable">
                <el-radio :label="1">账号可用</el-radio>
                <el-radio :label="0">不可用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="userType === '1'">
            <el-form-item label="所属租户" prop="tenantNo">
              <el-select style="width: 100%" v-model="editForm.tenantNo" placeholder="请选择所属租户">
                <el-option
                  v-for="item in tenantList"
                  :key="item.tenantNo"
                  :label="item.tenantName"
                  :value="item.tenantNo"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="model.userNo" label="微信昵称" prop="wxNickName">
              <el-input disabled placeholder="请输入微信昵称" v-model="editForm.wxNickName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="model.userNo" label="微信openId" prop="wxOpenId">
              <el-input disabled placeholder="请输入微信openId" v-model="editForm.wxOpenId"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input
                placeholder="请输入备注"
                type="textarea"
                v-model="editForm.remark"
                :maxlength="100"
                :autosize="{ minRows: 4, maxRows: 6 }"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCancel" size="small">取 消</el-button>
        <el-button type="primary" @click="handleOk('editFormRef')" size="small">确 定</el-button>
      </div>
    </el-dialog>

    <dept-tree-modal ref="deptModal" :checkDeptInfo="checkDeptInfo" @deptModalOk="deptModalOk"></dept-tree-modal>
  </div>
</template>

<script>
import pick from 'lodash.pick'
import { addUser, modifyUser, getTenantList } from '../js/auth'
import DeptTreeModal from './DeptTreeModal'
import { mapState } from 'vuex'
import { validatePassword, validEmail, validChinese, validEnAndCh } from '../js/validate'
import { sexList, idTypeList, userTypeList } from '../js/constants'
import md5 from 'md5'

export default {
  name: 'UserModal',
  components: { DeptTreeModal },
  data () {
    return {
      type: 'text',
      title: '添加用户',
      dialogVisible: false,
      isAdd: false,
      model: {},
      disabled: false, // 表单项的状态
      userShow: false,
      editForm: {
        account: '',
        nickName: '',
        userName: '',
        mobile: '',
        email: '',
        password: '',
        sex: '',
        age: '',
        roleNos: [],
        deptName: '',
        positionId: '',
        tenantNo: '',
        isEnable: '',
        employeeNo: '',
        employeeCardNo: '',
        idType: '',
        idcardNo: '',
        userType: [],
        remark: ''
      },
      rules: {
        account: [{ required: true, validator: validEnAndCh, trigger: 'change' }],
        userName: [{ required: true, validator: validChinese, trigger: 'change' }],
        mobile: [{ required: true, message: '请输入手机号!', trigger: 'blur' }],
        email: [{ required: true, validator: validEmail, trigger: 'blur' }],
        password: [{ required: true, validator: validatePassword, trigger: 'change' }],
        idcardNo: [{ required: false, validator: this.validateIdcardNo, trigger: 'blur' }],
        roleNos: [{ required: true, message: '请选择角色!', trigger: 'change' }],
        deptName: [{ required: true, message: '请选择部门!', trigger: 'change' }],
        positionId: [{ required: true, message: '请选择岗位!', trigger: 'change' }],
        tenantNo: [{ required: true, message: '请选择所属租户!', trigger: 'change' }],
        userType: [{ required: true, message: '请选择用户类型!', trigger: 'blur' }],
        employeeNo: [{ required: true, message: '请输入员工号!', trigger: 'blur' }],
        employeeCardNo: [{ required: true, message: '请输入员工卡号!', trigger: 'blur' }],
        isEnable: [{ required: true, message: '请选择状态!', trigger: 'change' }]
      },
      checkDeptInfo: {
        deptId: '',
        deptName: ''
      },
      sexList,
      idTypeList,
      userTypeList,
      tenantList: [],
      userType: JSON.parse(this.$base.getLocalStorage('User-Info')).userType,
      tenantNo: JSON.parse(this.$base.getLocalStorage('User-Info')).tenantNo
    }
  },
  watch: {
    // 校验规则替换
    disabled (val) {
      const {
        rules: { password }
      } = this
      if (val) {
        password[0].required = false
        password[0].validator = ''
      } else {
        password[0].required = true
        password[0].validator = validatePassword
      }
    },
    userType: {
      handler (val) {
        if (val === '1') {
          this.userTypeList.forEach((item) => {
            if (item.value !== '2') this.$set(item, 'disabled', true)
          })
        } else if (val === '2') {
          this.userTypeList.forEach((item) => {
            if (item.value === '1' || item.value === '2') this.$set(item, 'disabled', true)
          })
        }
      },
      immediate: true
    },
    'editForm.password' (val) {
      if (val) {
        this.type = 'password'
        this.$nextTick(() => {
          this.$refs.passwordRef1.blur()
          this.$refs.passwordRef2.focus()
        })
      } else {
        this.type = 'text'
        this.$nextTick(() => {
          this.$refs.passwordRef1.focus()
          this.$refs.passwordRef2.blur()
        })
      }
    }
  },
  computed: {
    ...mapState({
      roleList: (state) => state.auth.roleList,
      positionList: (state) => state.auth.positionList
    })
  },
  mounted () {
    // this.getTenantList()
  },
  methods: {
    validateIdcardNo (rule, value, callback) {
      if (value) {
        let reg = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
        if (value.length > 18) {
          callback(new Error('身份证号码不能超过18位!'))
        } else if (!reg.test(value)) {
          callback(new Error('请输入正确的身份证号码!'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    },

    // 新增
    add () {
      this.edit({})
    },

    // 编辑
    edit (record) {
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.editFormRef.clearValidate('password')
      })
      // record.positionId = Number(record.positionId)
      this.model = Object.assign({}, record)
      if (record.userNo) {
        this.disabled = true
        let ids = []
        const { userRoleList, deptId, deptName, userType } = record
        this.checkDeptInfo = {
          deptId,
          deptName
        }
        userRoleList.forEach((item) => {
          ids.push(item.roleNo)
        })

        this.$nextTick(() => {
          this.editForm.roleNos = ids
          this.editForm.userType = userType.split(',')
          // this.userType登录用户类型
          if (this.userType === '1') {
            this.userShow = false
          } else {
            // record.userType添加修改用户类型
            if ((record.userType === '1', record.userType === '2')) {
              this.userShow = false
            } else {
              this.userShow = true
            }
          }
          this.editForm = Object.assign(
            this.editForm,
            pick(
              this.model,
              'account',
              'nickName',
              'userName',
              'email',
              'mobile',
              'password',
              'sex',
              'age',
              'deptName',
              'positionId',
              'tenantNo',
              'idType',
              'idcardNo',
              'isEnable',
              'employeeNo',
              'employeeCardNo',
              'remark',
              'wxNickName',
              'wxOpenId'
            )
          )
        })
      } else {
        if (this.userType === '1') {
          this.userShow = false
        } else {
          this.userShow = true
        }
      }
    },

    // 提交表单
    handleOk (editFormRef) {
      this.$refs[editFormRef].validate(async (valid) => {
        if (valid) {
          let pMd5 = this.$base.randomString(3) + md5(this.editForm.password) + this.$base.randomString(3)

          const values = {
            ...this.editForm,
            userType: this.editForm.userType.join(','),
            deptId: this.checkDeptInfo.deptId,
            tenantNo: this.userType === 1 ? this.editForm.tenantNo : this.tenantNo,
            password: this.model.userNo ? undefined : pMd5
          }
          let res, msg
          if (!this.model.userNo) {
            res = await addUser(values)
            msg = '保存成功！'
          } else {
            res = await modifyUser(Object.assign({}, values, { userNo: this.model.userNo }))
            msg = '修改成功！'
          }
          if (res.code === 0) {
            this.$message.success(msg)
          } else {
            this.$message.warning(res.msg)
          }
          this.$emit('ok')
          this.handleCancel()
        }
      })
    },

    // 获取租户列表
    async getTenantList () {
      const { code, data, msg } = await getTenantList()
      if (code === 0) {
        this.tenantList = data
      } else {
        this.$message.warning(msg)
      }
    },

    // 上级部门弹框回调
    deptModalOk (val) {
      this.checkDeptInfo = val
      this.editForm.deptName = val.deptName
    },

    // 获取焦点弹框
    deptFocus () {
      this.$refs.deptModal.add()
      this.$refs.deptInput.blur()
    },

    // 取消
    handleCancel () {
      this.disabled = false
      this.dialogVisible = false
      this.$refs.editFormRef.resetFields()
      this.editForm.deptName = ''
      this.editForm.positionId = ''
      this.editForm.roleNos = []
      this.editForm.tenantNo = ''
      this.checkDeptInfo = {}
    }
  }
}
</script>

<style lang="scss" scoped>
/deep/ .userFormItem {
  margin-bottom: 17px;
}
.cus-input {
  position: absolute;
  left: -10000px;
}
</style>
